package com.powernode.controller;

import com.powernode.domain.SysMenu;
import com.powernode.model.Result;
import com.powernode.service.SysMenuService;
import com.powernode.util.AuthUtils;
import com.powernode.vo.MenuAndAuthVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Api(tags = "系统权限接口管理")
@RequestMapping("sys/menu")
@RestController
public class SysMenuController {
    @Autowired
    private SysMenuService sysMenuService;

    @ApiOperation("查询登录用户的菜单和权限")
    @GetMapping("nav")
    public Result<MenuAndAuthVo> loadUserMenuAndPerms() {
        // 获取当前登录用户ID
        Long userId = AuthUtils.getLoginUserId();

        // 获取用户菜单权限
        Set<SysMenu> sysMenuList = sysMenuService.queryUserMenuListByUserId(userId);

        // 获取用户的操作权限
        Set<String> perms = AuthUtils.getPerms();

        // 将菜单权限和操作权限封装到一个对象
        MenuAndAuthVo menuAndAuthVo = new MenuAndAuthVo();
        menuAndAuthVo.setAuthorities(perms);
        menuAndAuthVo.setMenuList(sysMenuList);

        return Result.success(menuAndAuthVo);
    }

    @ApiOperation("查询系统所有权限集合")
    @GetMapping("table")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result<List<SysMenu>> loadSysMenuList() {
        List<SysMenu> list = sysMenuService.queryAllSysMenuList();
        return Result.success(list);
    }

    @ApiOperation("新增权限")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result<String> saveSysMenu(@RequestBody SysMenu sysMenu) {
        Integer count = sysMenuService.addSysMenu(sysMenu);
        return Result.handle(count>0);
    }

//    sys/menu/info/326
    @ApiOperation("查询权限详情")
    @GetMapping("info/{menuId}")
    @PreAuthorize("hasAuthority('sys:menu:info')")
    public Result<SysMenu> loadSysMenuInfo(@PathVariable Long menuId) {
        SysMenu sysMenu = sysMenuService.getById(menuId);
        return Result.success(sysMenu);
    }

    @ApiOperation("修改权限信息")
    @PutMapping
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result<String> modifySysMenu(@RequestBody SysMenu sysMenu) {
        Integer count = sysMenuService.modifySysMenu(sysMenu);
        return Result.handle(count>0);
    }

    @ApiOperation("删除权限")
    @DeleteMapping("{menuId}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result<String> removeSysMenu(@PathVariable Long menuId) {
        Integer count = sysMenuService.removeSysMenuById(menuId);
        return Result.handle(count>0);
    }
}
